package com.tanhua.management.service;

import com.tanhua.management.mapper.UserFreezeMapper;
import com.tanhua.management.mapper.UserInfoMapper;
import com.tanhua.management.pojo.UserInfo;

import com.tanhua.management.vo.UserFreezeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * Author: sun
 * DateTime: 2021/4/27
 **/

@Service
public class UserFreezeService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserFreezeMapper userFreezeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String range = "FREEZE_RANGE_";


    //冻结用户;
    public Boolean freeze(UserFreezeVo userFreezeVo) {
        //拼接字符串，包含冻结用户的id，用于在redis中查询冻结用户;
        String rangeKey = range + userFreezeVo.getUserId();

        //根据用户id到mysql中查询该用户是否存在，如果不存在直接返回false;
        UserInfo userInfo = this.userInfoMapper.selectById(userFreezeVo.getUserId());
        if (null == userInfo) {
            return false;
        }
        //如果在redis中查询到数据，说明该用户已被冻结，直接返回false;
        if (this.redisTemplate.hasKey(rangeKey)) {
            return false;
        }

        //设置冻结范围：1为冻结登录，2为冻结发言，3为冻结发布动态;
        String range = userFreezeVo.getFreezingRange().toString();
        //设置冻结时间：1为冻结3天，2为冻结7天，3为永久冻结;
        int time = 0;
        switch (userFreezeVo.getFreezingTime()) {
            case 1:
                time = 3;
                break;
            case 2:
                time = 7;
                break;
            case 3:
                time = 36500;
                break;
        }
        //将冻结数据存入数据库和redis;
        this.redisTemplate.opsForValue().set(rangeKey, range, Duration.ofDays(time));

        //返回成功结果;
        return true;
    }


    //解冻用户;
    public Boolean unfreeze(UserFreezeVo userFreezeVo) {
        //拼接字符串;
        String rangeKey = range + userFreezeVo.getUserId();
        //删除redis数据，返回删除结果;
        return this.redisTemplate.delete(rangeKey);
    }
}
